//
//  YSPOauthController.swift
//  Weibo Demo
//
//  Created by 朴裕识 on 15/12/19.
//  Copyright © 2015年 Apple. All rights reserved.
//

import UIKit
import SVProgressHUD

class YSPOauthController: UIViewController, UIWebViewDelegate {
    
    //MARK: - webView代理方法
    //Sent after a web view starts loading a frame.
    func webViewDidStartLoad(webView: UIWebView) {
        // 显示正在加载
        // showWithStatus会一直显示
        // showInfoWithStatus,过1s自动关闭
        SVProgressHUD.showWithStatus("正在加载", maskType: SVProgressHUDMaskType.Gradient)
    }
    
    //Sent after a web view finishes loading a frame.
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    //Sent before a web view begins loading a frame.
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        let url = request.URL!.absoluteString

        //点授权时显示
        //request = Optional("http://www.baidu.com/?code=ef90f52b5ae13fab784048a106ae8915")
        //点取消时显示
        //request = Optional("http://www.baidu.com/?error_uri=%2Foauth2%2Fauthorize&error=access_denied&error_description=user%20denied%20your%20request.&error_code=21330")
        
        //现在开始要截取url中的code
        //如果不是点击授权或者取消，url就不是以授权回调地址（http://www.baidu.com/）开头(点击注册时就会这样)，直接让webView加载
        if !url.hasPrefix(YSPNetworkTool.sharedNetworkTool.redirect_uri) {
            return true
        }
        
        //到了这里证明确实点击了授权或者取消，开始截取code
        //URL.query就是url中问好后面的内容
        if let query = request.URL?.query {
            //进来了这里说明query有值
            let keyString = "code="
            //判断query的内容是否已code=开头
            if query.hasPrefix(keyString) {
                //截取code的值
                let queryNSString = query as NSString
                let code = queryNSString.substringFromIndex(keyString.characters.count)
//                print("code = \(code)")
                getAccessToken(code)
            }
        }
        else {
            print("query没有值")
        }
        return false
    }
    
    func getAccessToken(code: String) {
        YSPNetworkTool.sharedNetworkTool.getAccessToken(code) {(response, error) ->() in
            
            if error != nil && response == nil {
                print("error = \(error)")
                SVProgressHUD.showInfoWithStatus("没网速")
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
                    self.dismissController()
                })
                return
            }
            //能到这里说明没有错误
            //字典转模型
            //存到沙盒里
            let userAccount = YSPUserAccount.init(dictionary: response!)
            userAccount.saveUserAccount()
            
            (UIApplication.sharedApplication().delegate as! AppDelegate).switchViewController(false)
            
            self.dismissController()
        }
    }
    
    
    
    override func loadView() {
        //在这里直接给控制器的view复制，不用设置约束也会填充全屏
        //仅仅在只有一个view的时候适用
        view = webView
        
        //指定webView代理，监听加载的过程，以便加操作和动画
        webView.delegate = self
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        
        //加载登录页面
        let URL = YSPNetworkTool.sharedNetworkTool.getOauthURL()
        let request = NSURLRequest(URL: URL)
        webView.loadRequest(request)
        
        //设置导航栏按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "测试用", style: UIBarButtonItemStyle.Plain, target: self, action: "autoFill")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "dismissController")
        navigationItem.title = "授权登录"
        
    }
    
    //MARK: - 导航栏按钮事件响应
    //点击填充账号密码
    @objc private func autoFill() {
        // 创建js代码
        let js = "document.getElementById('userId').value='411454023@qq.com'; document.getElementById('passwd').value='qqwuqingxiao888';"
        
        webView.stringByEvaluatingJavaScriptFromString(js)
    }
    
    func dismissController() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    //MARK: - 懒加载
    private lazy var webView = UIWebView()
    
    
}
